
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId, getName, setName, removeName, getCookie, setCookie, removeCookie } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getHeadImg, removeHeadImg, setHeadImg } from '../../utils/auth'

const getDefaultState = () => {

    return {
        headImg: getHeadImg(), // 登录成功后的用户信息
        token: getToken(),
        name: getName(),
        userId:getUserId()
    }

}
const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_HEAD_IMG: (state, url) => {
        state.headImg = url
    },
    SET_USERID: (state, userId) => {
        state.userId = userId
    },
    // 用户注销
    loginOut(state) {
        state.userInfo = {}
        state.token=''
        sessionStorage.clear()
        localStorage.removeItem('token')
    },
}

const actions = {
    // 用户登录
    async login({ commit }, data) {
        return new Promise((resolve, reject) => {
            const { username, userId, handleImage } = data.userInfo
            commit('SET_NAME', username)
            commit('SET_TOKEN', data.token)
            commit('SET_HEAD_IMG', handleImage)
            commit('SET_USERID', userId)
            setToken(data.token)
            setName(username)
            setUserId(userId)
            setHeadImg(handleImage)
            resolve()
        }).catch(error => {
            reject(error)
        })
    },
    //注销
    async logout({ commit, state, rootState, dispatch }) {
        return new Promise((resolve, reject) => {           
                removeToken() 
                resetRouter()
                removeName()
                removeUserId()
                removeHeadImg()
                commit('RESET_STATE')
                dispatch('permission/removeRouter', {}, { root: true })
                resolve()
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
}
